package com.clip.service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Currency;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.sound.sampled.Clip;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.clip.dao.ClipEventDao;
import com.clip.dao.NoneuserClipMappingDAO;
import com.clip.dao.UserDAO;
import com.clip.dao.UserEmailDAO;
import com.clip.dao.UserEmailEventDAO;
import com.clip.entity.ClipEvent;
import com.clip.entity.NoneuserClipMapping;
import com.clip.entity.User;
import com.clip.entity.UserEmail;
import com.clip.entity.UserEmailEvent;
import com.clip.util.ToolsUtils;
import com.clip.util.mail.SimpleMailSender;

@Service
@Transactional
public class UserEmailService {
	@Autowired
	private UserEmailDAO userEmailDAO;
	@Autowired
	private UserDAO userDAO;
	@Autowired
	private UserEmailEventDAO userEmailEventDAO;
	@Autowired
	private NoneuserClipMappingDAO noneuserClipMappingDAO;
	@Autowired
	private ClipEventDao clipEventDao;
	public UserEmail getUserEmailByEmail(String email){
		UserEmail userEmail=null;
		List<UserEmail> list = userEmailDAO.findByEmail(email);
		if(list!=null&&list.size()>0){
			userEmail=list.get(0);
		}
		return userEmail;
	}
	public void updateUserEmail(UserEmail instance){
		userEmailDAO.attachDirty(instance);
	}
	public UserEmail addUserEmail(UserEmail instance){
		userEmailDAO.save(instance);
		return getUserEmailByEmail(instance.getEmail());
	}
	public void deleteEmail(int emailid,User currentUser){
		UserEmail userEmail = this.userEmailDAO.findById(emailid);
		if(userEmail!=null){
			if(userEmail.getUid()==currentUser.getId()){
				String hql = "UPDATE UserEmailEvent uel SET uel.status=1 WHERE uel.uid="+currentUser.getId()+" AND uel.type=2 AND uel.obj='"+userEmail.getEmail()+"'";
				userEmailEventDAO.executeQuery(hql);
				userEmailDAO.delete(userEmail);
			}
		}
	}
	public String activite(String activate){
		String result="此链接无效";
		UserEmailEvent uel = userEmailEventDAO.checkResetAuthorize(activate, 2,false);
		if(uel!=null){
			uel.setClick(1);
			User user = userDAO.findById(uel.getUid());
			if(user!=null){
				UserEmail userEmail = null;
				String hql = "SELECT ue FROM UserEmail ue WHERE ue.uid="+user.getId()+" AND ue.email='"+uel.getObj()+"'";
				List<UserEmail> list = userEmailDAO.findByQuery(hql);
				userEmail = list!=null&&list.size()>0 ? list.get(0) : null;
				if(userEmail!=null){
					userEmail.setBindable(1);
					userEmail.setStatus(1);
					userEmailDAO.attachDirty(userEmail);
				}else{
					userEmail = new UserEmail(user.getId(),uel.getObj(),1,1,"");
					userEmailDAO.save(userEmail);
				}
				userEmailEventDAO.delete(uel);
				result="验证成功";
			}else{
				result="验证失败";
			}
		}
		return result;
	}
	private void sendBindEmail(User user,UserEmail ue){
		Date date = new Date();
		UserEmailEvent uel = new UserEmailEvent(user.getId(),ue.getEmail(),"",2,date.getTime());
		if(userEmailEventDAO.save(uel)>0){
			String href = ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT)+"controlAjax!activite.action?status="+uel.getCode();
			String title="邮箱绑定验证邮件";
			Map<String, Object> root = new HashMap<String, Object>();
			root.put("name", user.getName());
			root.put("email", ue.getEmail());
			root.put("href", href);
			String mailcontent = com.clip.util.FtlUtils.stringRender(root,"bindEmailVerify.ftl");
			SimpleMailSender.send(mailcontent,user.getName()+"，你有一个来自档期的消息", ue.getEmail());
		}
	}
	/**
	 * 绑定邮箱
	 * @param user	登录用户
	 * @param userEmail 绑定Email
	 * @param send	是否发送邮件(如果userEmail.getBindable()=0 那么send=true)
	 * @return
	 */
	public String bindUserEmail(User user,UserEmail userEmail,Boolean send){
		String result="{result:'该邮箱已被绑定'}";
		if(this.getUserEmailByEmail(userEmail.getEmail())==null){
			UserEmail ue=addUserEmail(userEmail);
			if(ue!=null){
				if(send)
					sendBindEmail(user,ue);
				result="{result:'添加成功,请登录邮箱验证您的Email.'}";
			}else{
				result="{result:'添加失败.'}";
			}
		}
		return result;
	}
	public String saveUserEmail(UserEmail userEmail,String descInput,Integer status){
		String result="";
		String hql="FROM UserEmail ue where ue.uid="+userEmail.getUid()+" and ue.bindable=1 and ue.status=1";
		List<UserEmail> ueList = userEmailDAO.findByQuery(hql);
		
		if(ueList!=null&&ueList.size()>0){
			if(status.equals(1)){
				userEmail.setStatus(status);
				result="{result:'修改成功',flag:1}";
			}else{
				if(ueList.size()>1){
					userEmail.setStatus(status);
					result="{result:'修改成功',flag:1}";
				}else{
					result="{result:'至少设置一个邮箱为接受邮箱',flag:0}";
				}
			}
		}
		userEmail.setDescription(ToolsUtils.htmlEnCode(descInput));
		userEmailDAO.getSession().clear();
		userEmailDAO.attachDirty(userEmail);
		return result;
		
	}
	
	public UserEmail saveUserEmail(String email,User currentUser){
		String sql="from UserEmail ue where ue.email=?";
		List list=this.userEmailDAO.findByQuery(sql, new Object[]{email});
		if(list!=null&&list.size()>0){
			return null;
		}else{
			UserEmail userEmail=new UserEmail();
			userEmail.setBindable(0);
			userEmail.setStatus(1);
			userEmail.setContacttypeid(1);
			userEmail.setUid(currentUser.getId());
			userEmail.setEmail(email);
			userEmail.setDescription("");
			this.userEmailDAO.save(userEmail);
			sendBindEmail(currentUser,userEmail);
			return userEmail;
		}
	}
	
	
	public String resendEmail(User user,int emailid){
		String hql = "SELECT ue FROM UserEmail ue WHERE ue.uid=? AND ue.id=?";
		List<UserEmail> ueList = this.userEmailDAO.findByQuery(hql,new Object[]{user.getId(),emailid});
		UserEmail ue = null;
		ue = ueList!=null&&ueList.size()>0 ? ueList.get(0) : null;
		if(ue!=null){
			if(ue.getBindable()==0){
				sendBindEmail(user,ue);
			}
			return null;
		}else{
			return "需要验证的邮箱不存在";
		}
	}
	public Map<String,Object> getUserEmail(Integer uid){
		Map<String,Object> emailMap = new LinkedHashMap<String, Object>();
		List<UserEmail> userEmailList = userEmailDAO.findByUid(uid);
		for(UserEmail userEmail : userEmailList){
			Map<String,Object> map=new HashMap<String,Object>();
			map.put("Id", userEmail.getId());
			map.put("Uid", userEmail.getUid());
			map.put("Email", userEmail.getEmail());
			map.put("Status", userEmail.getStatus());
			map.put("Bindable", userEmail.getBindable());
			map.put("Description", userEmail.getDescription());
			map.put("Contacttypeid", userEmail.getContacttypeid());
			emailMap.put("email Eid="+userEmail.getId(), map);
		}
		return emailMap;
	}
	public void checkAndSendNoneuserClipEmail(User noneUser, int eventid) {
		String sql="from NoneuserClipMapping map where map.noneuid=? and map.eventid=?";
		List list=this.noneuserClipMappingDAO.findByQuery(sql,new Object[]{noneUser.getId(),eventid});
		if(list!=null&&list.size()>0){
			return;
		}else{
			NoneuserClipMapping mapping=new NoneuserClipMapping();
			mapping.setEventid(eventid);
			mapping.setNoneuid(noneUser.getId());
			this.noneuserClipMappingDAO.save(mapping);
			ClipEvent clipEvent=this.clipEventDao.findById(eventid);
			Map<String, Object> root=new HashMap<String, Object>();
			root.put("name", noneUser.getName());
			root.put("title", clipEvent.getTitle());
			String emailCoding=ToolsUtils.codingForUT(noneUser.getEmail());
			root.put("url", ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT)+"myclip/clip_detail.html?"+clipEvent.getShareid()+"_"+emailCoding);
			String mailcontent = com.clip.util.FtlUtils.stringRender(root,"noneuserclipEmail.ftl");
			SimpleMailSender.send(mailcontent,noneUser.getName()+"，你有一个来自档期的消息", noneUser.getEmail());
		}
	}
	
	public List<UserEmail> getUserEmailbyUid(int uid){
		List<String> emailList = new ArrayList<String>();
		String hql="from UserEmail ue where ue.uid="+uid;
		List<UserEmail> userEmailList = userDAO.findByQuery(hql);
		return userEmailList;
	}
	public String updateCCEmail(User currentUser, String emailInput) {
		String sql="from UserEmail ue where ue.uid=?";
		List list=this.userEmailDAO.findByQuery(sql, new Object[]{currentUser.getId()});
		UserEmail userEmail=null;
		if(list!=null&&list.size()>0){
			userEmail=(UserEmail) list.get(0);
			userEmail.setEmail(emailInput);
			userEmail.setBindable(0);
			this.userEmailDAO.attachDirty(userEmail);
		}else{
			userEmail=new UserEmail ();
			userEmail.setEmail(emailInput);
			userEmail.setBindable(0);
			userEmail.setUid(currentUser.getId());
			this.userEmailDAO.save(userEmail);
		}
		
		Calendar now=Calendar.getInstance();
		sql="from UserEmailEvent uee where uee.uid=? and uee.obj=? and uee.type=2 order by uee.actDate desc";
		List ueeList=this.userEmailEventDAO.findByQuery(sql, new Object[]{currentUser.getId(),userEmail.getEmail()});
		if(ueeList==null||ueeList.size()<=0){
			UserEmailEvent uel = new UserEmailEvent(currentUser.getId(),userEmail.getEmail(),"",2,now.getTimeInMillis());
			if(userEmailEventDAO.save(uel)>0){
				String href = ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT)+"controlAjax!activite.action?status="+uel.getCode();
				String title="邮箱绑定验证邮件";
				Map<String, Object> root = new HashMap<String, Object>();
				root.put("name", currentUser.getName());
				root.put("email", userEmail.getEmail());
				root.put("href", href);
				String mailcontent = com.clip.util.FtlUtils.stringRender(root,"bindEmailVerify.ftl");
				SimpleMailSender.send(mailcontent,currentUser.getName()+"，你有一个来自档期的消息", userEmail.getEmail());
			}
			return null;
		}else{
			UserEmailEvent uee=(UserEmailEvent) ueeList.get(0);
			long fivemintime=5*60*1000;
			if(now.getTimeInMillis()-uee.getActDate()>fivemintime){
				uee.setActDate(now.getTimeInMillis());
				this.userEmailEventDAO.update(uee);
				String href = ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT)+"controlAjax!activite.action?status="+uee.getCode();
				String title="邮箱绑定验证邮件";
				Map<String, Object> root = new HashMap<String, Object>();
				root.put("name", currentUser.getName());
				root.put("email", userEmail.getEmail());
				root.put("href", href);
				String mailcontent = com.clip.util.FtlUtils.stringRender(root,"bindEmailVerify.ftl");
				SimpleMailSender.send(mailcontent,currentUser.getName()+"，你有一个来自档期的消息", userEmail.getEmail());
				return null;
			}else{
				return "请勿频繁获取验证邮件(5分钟内不可再获取)";
			}
		}
	}
	public String resendCCInfoEmail(User currentUser, String emailInput) {
		Calendar now=Calendar.getInstance();
		String sql="from UserEmailEvent uee where uee.uid=? and uee.obj=? and uee.type=2 order by uee.actDate desc";
		List ueeList=this.userEmailEventDAO.findByQuery(sql, new Object[]{currentUser.getId(),emailInput});
		if(ueeList==null||ueeList.size()<=0){
			UserEmailEvent uel = new UserEmailEvent(currentUser.getId(),emailInput,"",2,now.getTimeInMillis());
			if(userEmailEventDAO.save(uel)>0){
				String href = ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT)+"controlAjax!activite.action?status="+uel.getCode();
				Map<String, Object> root = new HashMap<String, Object>();
				root.put("name", currentUser.getName());
				root.put("email", emailInput);
				root.put("href", href);
				String mailcontent = com.clip.util.FtlUtils.stringRender(root,"bindEmailVerify.ftl");
				SimpleMailSender.send(mailcontent,currentUser.getName()+"，你有一个来自档期的消息", emailInput);
			}
			return null;
		}else{
			UserEmailEvent uee=(UserEmailEvent) ueeList.get(0);
			long fivemintime=5*60*1000;
			if(now.getTimeInMillis()-uee.getActDate()>fivemintime){
				uee.setActDate(now.getTimeInMillis());
				this.userEmailEventDAO.update(uee);
				String href = ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT)+"controlAjax!activite.action?status="+uee.getCode();
				String title="邮箱绑定验证邮件";
				Map<String, Object> root = new HashMap<String, Object>();
				root.put("name", currentUser.getName());
				root.put("email", emailInput);
				root.put("href", href);
				String mailcontent = com.clip.util.FtlUtils.stringRender(root,"bindEmailVerify.ftl");
				SimpleMailSender.send(mailcontent,currentUser.getName()+"，你有一个来自档期的消息", emailInput);
				return null;
			}else{
				return "请勿频繁获取验证邮件(5分钟内不可再获取)";
			}
		}
	}
	public String updateUserEmail(User currentUser, int emailid, int emailaccept) {
		String sql="from UserEmail ue where ue.uid=? and ue.id=?";
		List list=this.userEmailDAO.findByQuery(sql, new Object[]{currentUser.getId(),emailid});
		if(list==null||list.size()!=1){
			return "该邮箱不存在或已被删除";
		}else{
			UserEmail userEmail=(UserEmail) list.get(0);
			userEmail.setStatus(emailaccept);
			this.userEmailDAO.attachDirty(userEmail);
			return null;
		}
	}
	public List getAvaiableUserEmailbyUid(int contactuid) {
		String sql="from UserEmail ue where ue.uid=? and ue.status=1 and ue.bindable=1";
		List list=this.userEmailDAO.findByQuery(sql, new Object[]{contactuid});
		return list;
	}
}
